#ifndef _MYSQL_CONNECTION
#define _MYSQL_CONNECTION

#include "../../../3rd/mysql/include/mysql.h"
#include "stdlib.h"
#include "../string_common.h"

#define CONNECT_STR_LENGTH		( 128 )

#define DB_LOG			"sql"

namespace sql
{
	class Statement;
	class PreparedStatement;
	class ResultSet;

	class Connection
	{
	private:
		common::StringTokens mConnectTocke;			// 数据库连接信息( 主机IP， 端口， 用户名， 密码， 数据库 )

		MYSQL* mMysql;

		static size_t db_count;

	private:
		bool do_query(const char* sql);

	public:
		Connection();
		~Connection();

		// 解析connString
		bool Init(const char* connString);
		bool Init(const std::string& host, const std::string& port, const std::string& user, const std::string& pwd, const std::string& db);
		// 连接数据库
		bool Connectioning();
		// 关闭连接
		void Close();
		// 连接是否由本地主动关闭（ 服务端关闭不包括 )
		bool IsClosed();

		int ExecuteUpdate(const char* sql);
		bool ExecuteUpdateNoBack(const char* sql);

		int ExecuteInsert(const char* sql);

		sql::ResultSet* ExecuteQuery(const char* sql, ResultSet& result_set);

		sql::Statement* createStatement();

		sql::PreparedStatement* prepareStatement(const char* sql);

		int BeginTransaction();
		int CommitTransaction();
		int RollbackTransaction();

		const char* GetConnectHost() { return mConnectTocke[0].c_str(); }
		unsigned int GetConnectPort() { return atoi(mConnectTocke[1].c_str()); }
		const char* GetConnectDB() { return mConnectTocke[4].c_str(); }
		const char* GetConnectUser() { return mConnectTocke[2].c_str(); }
		const char* GetConnectPwd() { return mConnectTocke[3].c_str(); }

		// 对于multiresult query, 清空所有result
		void ClearResult();

		unsigned long GetLastInsertID();

		const char* GetErrorString();
	private:
		unsigned int GetErrorCode();
	};

};

#endif


